const express = require('express');
const cors = require('cors');
const fileUpload = require('express-fileupload');
const path = require('path');
const fs = require('fs');
const sharp = require('sharp');
const archiver = require('archiver');
const { PDFDocument } = require('pdf-lib');

const app = express();
const port = 3001;

// 中间件
app.use(cors());
app.use(fileUpload({
  limits: { fileSize: 1024 * 1024 * 1024 }, // 1GB
  abortOnLimit: true
}));

// 创建上传目录
const uploadDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir);
}

// 文件转换
app.post('/api/convert', async (req, res) => {
  try {
    if (!req.files || !req.files.file) {
      return res.status(400).send('No file uploaded.');
    }

    const file = req.files.file;
    const format = req.body.format || 'pdf';
    
    // 这里应该添加实际的文件转换逻辑
    // 为演示目的，我们只是返回原文件
    res.send(file.data);
  } catch (error) {
    res.status(500).send('Error processing file');
  }
});

// 文件压缩
app.post('/api/compress', async (req, res) => {
  try {
    if (!req.files || !req.files.file) {
      return res.status(400).send('No file uploaded.');
    }

    const file = req.files.file;
    const format = req.body.format || 'zip';
    const archive = archiver(format);
    
    res.attachment(`compressed.${format}`);
    archive.pipe(res);
    
    const tempPath = path.join(uploadDir, file.name);
    await file.mv(tempPath);
    
    archive.file(tempPath, { name: file.name });
    await archive.finalize();
    
    fs.unlinkSync(tempPath);
  } catch (error) {
    res.status(500).send('Error compressing file');
  }
});

// 图片压缩
app.post('/api/compress-image', async (req, res) => {
  console.log('Received image compression request'); // 调试日志

  try {
    if (!req.files || !req.files.image) {
      console.log('No image file uploaded'); // 调试日志
      return res.status(400).send('No image uploaded.');
    }

    const image = req.files.image;
    const quality = parseInt(req.body.quality) || 80;
    
    console.log('Processing image:', image.name, 'with quality:', quality); // 调试日志

    // 验证文件类型
    if (!image.mimetype.startsWith('image/')) {
      return res.status(400).send('Invalid file type. Only images are allowed.');
    }

    try {
      const compressed = await sharp(image.data)
        .jpeg({ quality })
        .toBuffer();
      
      console.log('Image compressed successfully'); // 调试日志
      res.type('image/jpeg').send(compressed);
    } catch (sharpError) {
      console.error('Sharp processing error:', sharpError); // 调试日志
      res.status(500).send('Error processing image');
    }
  } catch (error) {
    console.error('Server error:', error); // 调试日志
    res.status(500).send('Error compressing image');
  }
});

// 图片转PDF
app.post('/api/images-to-pdf', async (req, res) => {
  try {
    if (!req.files || !req.files.images) {
      return res.status(400).send('No images uploaded.');
    }

    const images = Array.isArray(req.files.images) 
      ? req.files.images 
      : [req.files.images];

    const pdfDoc = await PDFDocument.create();
    
    for (const image of images) {
      const img = await sharp(image.data)
        .jpeg()
        .toBuffer();
      
      const jpgImage = await pdfDoc.embedJpg(img);
      const page = pdfDoc.addPage();
      
      const { width, height } = page.getSize();
      page.drawImage(jpgImage, {
        x: 0,
        y: 0,
        width,
        height,
      });
    }
    
    const pdfBytes = await pdfDoc.save();
    res.type('application/pdf').send(Buffer.from(pdfBytes));
  } catch (error) {
    res.status(500).send('Error creating PDF');
  }
});

// 去除图片水印
app.post('/api/remove-watermark', async (req, res) => {
  try {
    if (!req.files || !req.files.image) {
      return res.status(400).send('No image uploaded.');
    }

    const image = req.files.image;
    
    // 这里应该添加实际的水印去除逻辑
    // 为演示目的，我们只是返回原图
    const processed = await sharp(image.data)
      .toBuffer();
    
    res.type('image/png').send(processed);
  } catch (error) {
    res.status(500).send('Error removing watermark');
  }
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
}); 